/*
 * iShopPlace Project.
 */
package ishopplace.view.util;

import ishopplace.view.bean.AccountBean;
import ishopplace.view.bean.BeanNames;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * This Filter class handle the security of the application.
 * <p>
 * It should be configured inside the web.xml.
 * 
 * @author <a href="mailto:derek@derekshen.com">Derek Y. Shen</a>
 */
public class SecurityFilter implements Filter {
	//the login page uri
	private static final String SIGNON_PAGE_URI = "signon.jsf";
	
	//the logger object
	private Log logger = LogFactory.getLog(this.getClass());
	
	//a set of restricted resources
	private Set restrictedResources;
	
	/**
	 * Initializes the Filter.
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.restrictedResources = new HashSet();
		this.restrictedResources.add("/account.jsf");
		this.restrictedResources.add("/createOrder.jsf");
	}
	
	/**
	 * Standard doFilter method.
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		this.logger.debug("doFilter");
		HttpServletRequest request = (HttpServletRequest)req;
		String url = request.getServletPath();
		String query = request.getQueryString();
		this.logger.debug("url = " + url);
		this.logger.debug("query = " + query);
		
		if (this.contains(url) && !this.authorize((HttpServletRequest)req)) {
			this.logger.debug("authorization failed");
		    if (query != null) {
		        request.getSession().setAttribute("origRequestUri", url+"?"+query);
		    } else {
		        request.getSession().setAttribute("origRequestUri", url);
		    }
			request.getRequestDispatcher(SIGNON_PAGE_URI).forward(req, res);
		}
		else {
			this.logger.debug("authorization succeeded");
			chain.doFilter(req, res);
		}
	}
	
	public void destroy() {} 
	
	/**
	 * Check to see if the restricted resource is requested.
	 * 
	 * @param url the requested resource url
	 * @return true if yes, false otherwise
	 */
	private boolean contains(String url) {
		Iterator ite = this.restrictedResources.iterator();
		while (ite.hasNext()) {
			String restrictedResource = (String)ite.next();
			
			if (restrictedResource.equalsIgnoreCase(url)) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Authorize the current user.
	 * 
	 * @param req the http servlet request
	 * @return true if authorized, false otherwise
	 */
	private boolean authorize(HttpServletRequest req) {
		AccountBean user = (AccountBean)req.getSession().getAttribute(BeanNames.ACCOUNT_BEAN);
		return (user != null && user.isLoggedin());
	}
}
